#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

// IP
// port
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        LogSpace::Logger::LogMessage(LogSpace::LogLevel::FATAL,"Socket",1,LogSpace::log) << "Argv Fail!";
        return 1;
    }

    std::string ip(argv[1]);
    uint16_t port = std::stoi(argv[2]);

    int socketfd = socket(AF_INET,SOCK_DGRAM,0);

    if(socketfd < 0)
    {
        LogSpace::Logger::LogMessage(LogSpace::LogLevel::FATAL,"Socket",1,LogSpace::log) << "Socket Fail!";
        return 2;
    }

    struct sockaddr_in send;
    // 清零。
    bzero(&send,sizeof(send));
    send.sin_family = AF_INET;
    // 将网络序列转为本地序列。
    send.sin_port = ntohs(port);
    send.sin_addr.s_addr = inet_addr(ip.c_str());

    while(true)
    {
        // 发送消息，连接上服务端。需要初始化sockaddr_in
        std::string message;
        std::cout << "Please Enter #";
        std::getline(std::cin,message);
        int m = sendto(socketfd,message.c_str(),message.size(),0,(struct sockaddr*)&send,sizeof(send));

        (void)m;

        // 收消息。无需初始化sockaddr_in，但是要传长度地址。
        char buffer[1024];
        struct sockaddr_in receive;
        socklen_t len = sizeof(receive);
        ssize_t n = recvfrom(socketfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&receive,&len);

        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}